import axios from 'axios';
import dotenv from 'dotenv';
import { getTokenFromStore } from '../../auth/tokenStore.js';
import { getMyProject } from '../../auth/projectStore.js';

dotenv.config();

// 华为云 IoTDA 设备创建函数（完整版）
async function addDevice(deviceData) {
  // 1. 环境检查
  if (!process.env.IOTDAEndpoint) {
    throw new Error('IOTDAEndpoint 未在 .env 文件中定义');
  }

  // 2. 输入数据验证
  const requiredFields = ['product_id', 'device_id', 'node_id'];
  const missingFields = requiredFields.filter(field => !deviceData?.[field]);
  
  if (missingFields.length > 0) {
    throw new Error(`缺少必填字段: ${missingFields.join(', ')}`);
  }

  // 3. 获取认证信息
  const token = getTokenFromStore();
  const projectId = getMyProject();
  
  if (!token || !projectId) {
    throw new Error('认证失败: 缺少 Token 或 Project ID');
  }

  // 4. 构造华为云 API 请求体（严格匹配官方文档）
  const payload = {
    device_id: deviceData.device_id,
    node_id: deviceData.node_id,
    product_id: deviceData.product_id,
    device_name: deviceData.device_name || deviceData.device_id,
    description: deviceData.description || '',
    tags: (deviceData.tags || []).map(tag => ({
      tag_key: tag.key || 'unnamed',
      tag_value: tag.value || ''
    })),
    extension_info: {
      manufacturer: deviceData.manufacturer || 'unknown',
      model: deviceData.model || 'default',
      service_capability: deviceData.capabilities || []
    }
  };

  // 5. 发送请求
  try {
    const response = await axios.post(
      `https://${process.env.IOTDAEndpoint}/v5/iot/${projectId}/devices`,
      payload,
      {
        headers: {
          'X-Auth-Token': token,
          'Content-Type': 'application/json'
        },
        timeout: 5000 // 5秒超时
      }
    );

    // 返回华为云原始响应数据
    return {
      success: true,
      deviceId: response.data.device_id,
      result: response.data
    };
  } catch (error) {
    // 6. 增强错误处理
    const errorInfo = {
      status: error.response?.status || 'NETWORK_ERROR',
      message: error.response?.data?.message || error.message,
      details: error.response?.data || null
    };

    console.error('华为云设备创建失败:', JSON.stringify(errorInfo, null, 2));
    throw new Error(`设备创建失败: ${errorInfo.message}`);
  }
}

export { addDevice };